package com.board.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.AlipayApiException;
import com.board.dto.SeatOrderDto;
import com.board.dto.SendOrderDto;
import com.board.dto.SendOrderGetDto;
import com.board.dto.SendOrderOutDto;
import com.board.entity.SendOrder;
import com.board.form.*;
import com.board.param.OrderRefundParam;
import com.board.param.SeatOrderParam;
import com.board.param.StoreOutSendOrderParam;
import com.board.param.UserFindSeatOrderParam;
import com.board.service.SeatEatOrderService;
import com.board.service.SendOrderService;
import com.board.util.JwtUtil;
import com.board.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 膳食系统-派送订单表 前端控制器
 * </p>
 *
 * @author 小叶
 * @since 2024年04月04日
 */
@RestController
@RequestMapping("/sendOrder")
@Api(tags = "外送订单接口")
public class SendOrderController {

    @Autowired
    private SeatEatOrderService seos;
    @Autowired
    private SendOrderService sendOrderService;

    /**
     * 用户创建外送订单
     * @param form 传递的订单信息，包含菜品id和数量、餐厅和商店id、备注
     * @param token 新增订单的用户token信息
     * @return 返回新增的订单信息
     */
    @PostMapping("/createOrder")
    @ApiOperation("用户创建外送订单")
    public Result createOrder(@RequestBody SendOrderForm form, @RequestHeader String token){
        Integer userId = (Integer) JwtUtil.getData(token, "subject");
        SeatOrderParam param = BeanUtil.toBean(form, SeatOrderParam.class);
        param.setOrderType(1);
        SendOrderDto dto = ((SendOrderDto) seos.createOrder(param, userId));
        return Result.success("生成外送订单成功",dto);
    }

    /**
     * 用户查询外送订单
     * @param form 查询条件，包含时间段、商店、餐厅
     * @param token 用户token
     * @return 返回查询结果
     */
    @GetMapping("/userFindOrder")
    @ApiOperation("用户条件查询外送订单")
    public Result userFindOrder(UserFindSendOrderForm form, @RequestHeader String token){
        Integer userId = (Integer) JwtUtil.getData(token, "subject");
        List<SendOrderDto> dtos = sendOrderService.userFindOrder(BeanUtil.toBean(form, UserFindSeatOrderParam.class),userId);
        return Result.success("查看外送订单成功",dtos);
    }

    /**
     * 支付宝调用的外送订单支付回调接口
     * @param request 支付宝传递过来的参数
     * @return 返回成功给到支付宝
     * @throws AlipayApiException
     */
    @PostMapping("/orderCallBack")
    @ApiOperation("外送订单支付回调接口")
    public String orderCallBack(HttpServletRequest request) throws AlipayApiException {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        params.put("order_type","1");
        seos.orderCallBack(params);
        return "SUCCESS";
    }

    /**
     * 用户收到派送的订单
     * @param orderNum 取餐的订单号
     * @param token 用户token
     * @return 返回的取餐信息
     */
    @PostMapping("/userGetFood")
    @ApiOperation("用户收到派送单")
    public Result userGetFood(String orderNum,@RequestHeader String token){
        Integer userId = (Integer) JwtUtil.getData(token, "subject");
        Integer orderType = 1;
        SendOrderGetDto dto = ((SendOrderGetDto) seos.userGetFood(orderNum, userId, orderType));
        return Result.success("操作成功",dto);
    }


    /**
     * 用户提交外送退款申请
     * @param form 退款提交的内容，包含订单号、退款理由
     * @param token 用户token
     * @return 返回退款的订单信息
     * @throws AlipayApiException
     */
//    @PostMapping("/refund")
//    @ApiOperation("用户提交外送退款申请")
//    public Result refund(@RequestBody OrderRefundForm form, @RequestHeader String token) throws AlipayApiException {
//        Integer userId = (Integer) JwtUtil.getData(token, "id");
//        SeatOrderDto dto = seos.refund(BeanUtil.toBean(form, OrderRefundParam.class),userId);
//        return Result.success("用户提交外送退款成功",dto);
//    }


    /**
     * 商家出餐外送订单
     * @param form 出餐订单信息，包含订单号、送货人员、送货人员电话
     * @param token 商家token
     * @return 返回出餐的订单信息
     */
    @PostMapping("/storeOutSendOrder")
    @ApiOperation("商家出餐外送订单")
    public Result storeOutSendOrder(@RequestBody StoreOutSendOrderForm form,@RequestHeader String token){
        Integer storeId = (Integer) JwtUtil.getData(token, "store_id");
        SendOrderOutDto dto =  sendOrderService.storeOutSendOrder(BeanUtil.toBean(form, StoreOutSendOrderParam.class),storeId);
        return Result.success("商家出餐完成",dto);
    }

    @PostMapping("/storeConfirmOrder")
    @ApiOperation("商家确认送达")
    public Result storeConfirmOrder(String orderNum,@RequestHeader String token){
        Integer storeId = (Integer) JwtUtil.getData(token, "store_id");
        SendOrderOutDto dto =  sendOrderService.storeConfirmOrder(orderNum,storeId);
        return Result.success("商家确认送达",dto);
    }

}

